const express = require('express')
const path = require('path')
const fs = require('fs')
const multer = require('multer')
const router = express.Router()
const { exec, getAll, getOne } = require('../db')

router.post(
  '/img',
  multer({
    //设置文件存储路径
    dest: 'uploads/images', //upload文件如果不存在则会自己创建一个。
  }).single('file'),
  (req, res) => {
    let oldname = req.file.path
    let newname = req.file.path + path.parse(req.file.originalname).ext //.jpg
    fs.renameSync(oldname, newname) //将老的文件名改成新的有后缀的文件 #同步写法
    res.send({
      code: 0,
      url:
        'http://localhost:3000/upload/' +
        req.file.filename +
        path.parse(req.file.originalname).ext, // 返回给浏览器一个磁盘地址和请求路径
    })
  }
)

router.post('/del', (req, res) => {
  const { url } = req.body
  const arr = url.split('/')
  const delName = arr[arr.length - 1]
  fs.unlink(`./uploads/images/${delName}`, (err) => {
    if (err) {
      res.send({
        code: 500,
        message: '文件删除失败',
      })
      return
    }
    res.send({
      code: 0,
      message: '文件删除成功',
    })
  })
})
// 新增文章
router.post('/', async (req, res) => {
  // 一. 解析参数
  const { author, title, content, imgPath, type, identify, location } = req.body
  let sql = `select id from blog_category where type = '${type}'`
  const { id } = await getOne(sql)
  sql = `insert into blog_articles (author,title,content,category_id,imgPath,identify,location) values('${author}','${title}','${content}',${id},'${imgPath}','${identify}','${location}')`
  // console.log(sql)
  const data = await exec(sql)
  // console.log(data)
  // 三. 返回结果
  res.send({
    code: 0,
    message: '添加文章成功',
    result: {
      id: data.insertId,
      author,
      title,
      content,
      imgPath,
      category_id: id,
    },
  })
})

module.exports = router
